<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            height: 1500px;
            position: relative;
        }

        .nav {
            background-color: #ccc;
            height: 30px;
            width: 100%;
            position: relative;
            top: 60px;
        }
    </style>
</head>

<body>
    <div class="nav"></div>
    <script>
        var nav = document.querySelector('.nav')
        var navOffsetTop = nav.offsetTop
        window.onscroll = function () {
            if (getScrollTop() >= navOffsetTop) {
                nav.style.position = 'fixed'
                nav.style.top = '0px'
            } else {
                // 往回滚动的时候
                nav.style.position = 'relative'
                nav.style.top = '60px'
            }
        }

        function getScrollTop() {
            return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop
        }
    </script>
</body>

</html>